const Captchapng = require('captchapng2');
const userModel = require('../models/user');

const showRegister = async (ctx, next) => {
    await ctx.render('register');
}
const showLogin = async (ctx, next) => {
    await ctx.render('login');
}
const getUsers = async (ctx, next) => {
    let users = await userModel.queryUser();
    ctx.body = users;
}

// 检查用户名是否存在
const checkUsername = async (ctx, next) => {
    let { username } = ctx.request.body;
    let users = await userModel.findUserByUsername(username);

    if (users.length === 0) {
        ctx.body = { code: '001', msg: '可以注册' };
        return;
    }

    ctx.body = { code: '002', msg: '用户名已存在' };
}

// 注册
const doRegister = async (ctx, next) => {
    try {
        let { username, password, email, v_code } = ctx.request.body;

        // 验证验证码
        if (v_code !== ctx.session.v_code) {
            ctx.body = { code: '002', msg: '验证码不正确' };
            return;
        }

        // 判断用户名是否存在
        let users = await userModel.findUserByUsername(username);
        if (users.length !== 0) {
            ctx.body = { code: '002', msg: '用户名已存在' };
            return;
        }

        // 注册
        let newUser = new userModel({ username, password, email });

        let result = await userModel.registerUser(newUser);
        // insertId / rows  判断是否插入成功   再给予提示
        if (result.affectedRows === 1) {
            ctx.body = { code: '001', msg: '注册成功' };
            return;
        }
        ctx.body = { code: '002', msg: '注册失败' + result.message };

    } catch (e) {
        ctx.throw(e);
    }
}

// 登录
const doLogin = async (ctx, next) => {
    let { username, password } = ctx.request.body;

    // 验证用户名正确性
    let users = await userModel.findUserByUsername(username);
    // console.log(users);
    if (users.length === 0) {
        ctx.body = { code: '002', msg: '用户名或密码不正确' };
        return;
    }
    // 验证密码正确性
    let user = users[0];
    if (user.password === password) {
        ctx.session.user = user;
        ctx.body = { code: '001', msg: '登录成功' };
        return;
    }
    ctx.body = { code: '002', msg: '用户名或密码不正确' };
}

// 验证码
const getPic = async (ctx, next) => {
    let rand = parseInt(Math.random() * 9000 + 1000);
    // 区分不同用户的答案，并分配 session, 响应 cookie
    ctx.session.v_code = rand + '';
    let png = new Captchapng(80, 30, rand);
    ctx.body = png.getBuffer();
}

// 退出登录
const logout = async(ctx, next) => {
    ctx.session.user = null;
    ctx.redirect('/user/login');
}

module.exports = {
    showRegister,
    showLogin,
    getUsers,
    checkUsername,
    doRegister,
    doLogin,
    logout,
    getPic,
}